package com.szp.spCloud.user.service;

import com.szp.spCloud.common.pojo.Token;
import com.szp.spCloud.common.pojo.User;
import com.szp.spCloud.user.dao.TokenRepository;
import com.szp.spCloud.user.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    UserRepository userRepository;
    @Autowired
    TokenRepository tokenRepository;

//    @Reference
//    CodeValidateService codeValidateService;

    public int register(String email, String password, String  code){
        // check isRegister
        if(this.isRegistered(email))
            return  1;
        // validate code;

        // register
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setUsername(email);
        user.setCreateTime(new Date(System.currentTimeMillis()));
        userRepository.save(user);
        return 0;
    }


    public boolean isRegistered (String email){
        User user = new User();
        user.setEmail(email);
        List<User> res = userRepository.findAll(Example.of(user));
        return null != res && res.size() > 0;
    }

    public String login(String email, String password){
        // check email, password
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        List<User> res = userRepository.findAll(Example.of(user));
        if(res == null || res.size() == 0)
            return null;
        // generate token
        String tokenStr = UUID.randomUUID().toString();

        // delete old token
        Token token = new Token();
        token.setEmail(email);
        tokenRepository.deleteByEmail(email);
        // save tokern
        token.setToken(tokenStr);
        tokenRepository.save(token);
        return tokenStr;
    }

//    public int validateCode(String email, String code) {
//        return codeValidateService.validateCode(email, code);
//    }

//    public String info(String tokenStr){
//        Token token = new Token();
//        token.setToken(tokenStr);
//        Optional<Token> res = tokenRepository.findOne(Example.of(token));
//        if(res.isPresent()){
//            return res.get().getEmail();
//        }
//        return null;
//    }
}
